package com.tarim.streetdance.api;

import com.alibaba.fastjson.JSONObject;
import com.tarim.streetdance.model.*;
import com.tarim.streetdance.service.FileSystemService;
import com.tarim.streetdance.service.VideoService;
import com.tarim.streetdance.service.VideoViewsService;
import com.tarim.streetdance.util.Constants;
import com.tarim.streetdance.util.JsonResult;
import com.tarim.streetdance.util.RedisUtil;
import com.tarim.streetdance.util.UploadFileUtil;
import com.tarim.streetdance.vo.Criteria;
import com.tarim.streetdance.vo.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/api/video")
public class VideoApi {
    @Autowired
    private VideoService videoService;
    @Autowired
    private VideoViewsService videoViewsService;
    @Autowired
    private FileSystemService fileSystemService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 发布
     * @param param
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/insert")
    public JsonResult insert (@RequestBody Map param, HttpServletRequest request, HttpServletResponse response) {
        JsonResult jsonResult;
        try {
            List<Type> typeList = JSONObject.parseArray(param.get("typeList").toString(), Type.class);
            VideoWithBLOBs video = JSONObject.parseObject(param.get("video").toString(), VideoWithBLOBs.class);
            if (video.getFileId() == null || video.getFileId().equals("")) {
                jsonResult = new JsonResult(Constants.STATUS_FAIL, "请上传视频文件");
                return jsonResult;
            }
            if (video.getThumb() == null || video.getThumb().equals("")) {
                FileSystemWithBLOBs file = fileSystemService.selectByPrimaryKey(video.getFileId());
                FileSystemWithBLOBs imageFile = UploadFileUtil.getTempPath(file.getFilepath());
                fileSystemService.insertSelective(imageFile);
                video.setThumb(imageFile.getUrl());
            }
            Object object = redisUtil.get(request.getHeader("token"));
            if (object == null) {
                jsonResult = new JsonResult(Constants.STATUS_FAIL, "登录后可发布视频");
                return jsonResult;
            }
            JSONObject jsonObject = (JSONObject) object;
            User user = jsonObject.toJavaObject(User.class);
            video.setUserId(user.getId());
            video.setUserCode(user.getUserCode());
            video.setUserName(user.getUserName());
            video.setTypeList(typeList);
            int i = videoService.insertSelective(video);
            if (i != 0) {
                jsonResult = new JsonResult(Constants.STATUS_SUCCESS, "发布成功，待管理员审核");
            }else {
                jsonResult = new JsonResult(Constants.STATUS_FAIL, "发布失败，请稍后重试");
            }
        }catch (Exception e) {
            e.printStackTrace();
            jsonResult = new JsonResult(Constants.STATUS_ERROR, "系统异常,请联系管理员");
        }
        return jsonResult;
    }

    /**
     * 根据类别查视频
     * @param pageIndex
     * @param pageSize
     * @param typeId
     * @return
     */
    @RequestMapping("/selectVideoByType")
    public JsonResult selectVideoByType (@RequestParam(value = "pageIndex", defaultValue = "0") Integer pageIndex,
                                         @RequestParam(value = "pageSize", defaultValue = "40") Integer pageSize,
                                         @RequestParam(value = "typeId") Long typeId,
                                         @RequestParam(value = "collegeId", defaultValue = "") Long collegeId) {
        JsonResult jsonResult;
        try {
            PageBean<VideoWithBLOBs> pageBean = new PageBean<>(pageIndex, pageSize);
            VideoWithBLOBs videoWithBLOBs = new VideoWithBLOBs();
            videoWithBLOBs.addExtField("typeId", typeId);
            videoWithBLOBs.addExtField("collegeId", collegeId);
            pageBean = videoService.selectVideoByType(pageBean, videoWithBLOBs);
            jsonResult = new JsonResult(Constants.STATUS_SUCCESS, "成功", pageBean);
        }catch (Exception e) {
            e.printStackTrace();
            jsonResult = new JsonResult(Constants.STATUS_ERROR, "系统异常，请联系管理员");
        }
        return jsonResult;
    }

    /**
     * 查询视频带评论
     * @param id
     * @return
     */
    @RequestMapping(value = "/selectById", method = RequestMethod.POST)
    public JsonResult selectById (HttpServletRequest request, Long id) {
        JsonResult jsonResult;
        try {
            VideoWithBLOBs videoWithBLOBs = videoService.selectByPrimaryKey(id);
            if (videoWithBLOBs == null){
                jsonResult = new JsonResult(Constants.STATUS_FAIL, "失败");
            }else {
                /*Object object = redisUtil.get(request.getHeader("token"));
                if (object != null) {
                    JSONObject jsonObject = (JSONObject) object;
                    User user = jsonObject.toJavaObject(User.class);
                    if (user.getId() != videoWithBLOBs.getUserId()){
                        VideoViews videoViews = new VideoViews();
                        videoViews.setUserId(user.getId());
                        videoViews.setVideoId(videoWithBLOBs.getId());
                        videoViewsService.insertSelective(videoViews);
                    }
                }*/
                jsonResult = new JsonResult(Constants.STATUS_SUCCESS, "成功", videoWithBLOBs);
            }
        }catch (Exception e) {
            e.printStackTrace();
            jsonResult = new JsonResult(Constants.STATUS_ERROR, "系统异常，请联系管理员");
        }
        return jsonResult;
    }

    /**
     * 根据用户ID模糊查询视频
     * @param userId
     * @param title
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @RequestMapping("/selectVideoByUserId")
    public JsonResult selectVideoByUserId (@RequestParam(value = "userId", defaultValue = "") Long userId,
                                           @RequestParam(value = "status", defaultValue = "0") String status,
                                           @RequestParam(value = "title", defaultValue = "") String title,
                                           @RequestParam(value = "pageIndex", defaultValue = "0") Integer pageIndex,
                                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        JsonResult jsonResult;
        try {
            PageBean<VideoWithBLOBs> pageBean = new PageBean(pageIndex, pageSize);
            VideoWithBLOBs record= new VideoWithBLOBs();
            record.addExtField("userId", userId);
            record.addExtField("status", status);
            record.addExtField("title", title);
            pageBean = videoService.selectVideoByUserId(pageBean, record);
            List<Map> stateNumList = videoService.selectStateNum();
            Map<String, Object> result = new HashMap<>();
            result.put("state", stateNumList);
            result.put("data", pageBean);
            jsonResult = new JsonResult(Constants.STATUS_SUCCESS, "成功", result);
        }catch (Exception e) {
            e.printStackTrace();
            jsonResult = new JsonResult(Constants.STATUS_ERROR, "系统异常，请联系管理员");
        }
        return jsonResult;
    }

    /**
     * 删除视频
     * @param video
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public JsonResult updateForDelete (Video video) {
        JsonResult jsonResult;
        try {
            int i = videoService.updateForDelete(video);
            if (i != 0) {
                jsonResult = new JsonResult(Constants.STATUS_SUCCESS, "删除成功");
            }else {
                jsonResult = new JsonResult(Constants.STATUS_FAIL, "删除失败");
            }
        }catch (Exception ex) {
            ex.printStackTrace();
            jsonResult = new JsonResult(Constants.STATUS_ERROR, "系统异常，请联系管理员");
        }
        return jsonResult;
    }
}
